import FormFilter from '@/components/ManageFormFilter/FormFilter';
import UserModal from '@/components/UserManage/userModal';
import {
  DeleteOutlined,
  PhoneOutlined,
  RedoOutlined,
  SearchOutlined,
  TeamOutlined,
  TwitterOutlined,
  UserAddOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-components';
import {
  Button,
  Card,
  Checkbox,
  Col,
  Form,
  Input,
  message,
  Modal,
  Popconfirm,
  Row,
  Table,
  Tag,
} from 'antd';
import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'umi';

class UserManager extends Component {
  componentDidMount() {
    // 当页面组件完全的加载完毕触发此生命周期，只会触发一次
    this.formRef = React.createRef();
    this.modalRef = React.createRef();
    this.tableRef = React.createRef();
    //初始数据加载
    this.handleRefreshData();
  }

  // componentDidUpdate() {
  //   this.handleRefreshData();
  // }

  //请求table表数据
  handleRefreshData() {
    let formData = {};
    try {
      const getFormData = this.formRef.current.getFieldsValue();
      formData = { ...getFormData };
    } catch (e) {
      formData = undefined;
    }
    // 获取表格数据
    const { dispatch } = this.props;
    // 对表单数据处理，权限改成字符串逗号隔开
    if (formData && formData.roleName) {
      formData.roleName = formData.roleName.join(',');
    }
    dispatch({
      type: 'userManage/changeLoadingStatus',
    });
    if (dispatch) {
      dispatch({
        type: 'userManage/getData',
        payload: formData ? { formData } : {},
      });
    }
  }

  //重置查询表单
  resetAllFields() {
    const { current } = this.formRef;
    current.resetFields();
  }

  //新增/修改Model
  changeModal(type = 'add', data = {}) {
    const { dispatch } = this.props;
    dispatch &&
      dispatch({
        type: 'userManage/changeModalVisibleAndSetValue',
        payload:
          type === 'update'
            ? {
                type,
                data,
              }
            : {
                type,
              },
      });
  }

  changePage(currentPage) {
    const { dispatch } = this.props;
    dispatch &&
      dispatch({
        type: 'userManage/changePage',
        payload: currentPage,
      }).then(() => {
        this.handleRefreshData();
      });
  }

  submitUserInfo(type = 'add') {
    // 修改用户信息
    const { dispatch, userDetail } = this.props;
    const { current } = this.modalRef;
    const formRef = _.get(current, 'formRef.current', {});
    let values = formRef.getFieldsValue();
    if (!_.isString(values.address)) {
      values.address = values.address.join('/');
    }

    dispatch &&
      dispatch({
        type: 'userManage/submitUserInfo',
        payload: {
          type,
          formData: {
            ...userDetail,
            ...values,
          },
        },

        callback: (res) => {
          if (res.code == 200) {
            message.success(`${type === 'add' ? '添加' : '修改'}成功`);
            this.changeModal(); // 关闭模态框
            this.clearUserDetail(); // 清除redux中用户管理的用户数据
            const modalForm = _.get(current, 'formRef.current', {});
            modalForm.resetAllFields && modalForm.resetAllFields(); // 清除modal中表单数据
            this.handleRefreshData(); // 刷新列表
          } else {
            message.error(res.message);
          }
        },
      });
  }

  //清空UserDetail值
  clearUserDetail() {
    const { dispatch } = this.props;
    dispatch &&
      dispatch({
        type: 'userManage/clearUserDetail',
      });
  }

  //删除用户根据id
  deleteUserById(record) {
    const { dispatch } = this.props;

    //删除用户
    dispatch &&
      dispatch({
        type: 'userManage/deleteUserInfo',
        payload: record,

        callback: (res) => {
          if (res.code == 200) {
            message.success(`删除成功`);
            this.handleRefreshData(); // 刷新列表
          } else {
            message.error(res.message);
          }
        },
      });
  }

  render() {
    const {
      users,
      loading,
      selectedRowsKeys = [],
      dispatch,
      modalVisible,
      userDetail,
      pagination,
      effectPageInfo,
      troops,
      currentUser,
    } = this.props;
    let { columns = [] } = this.props;
    const formName = '用户条件搜索';
    const tableName = '用户列表';

    // const hasPermission = (allowedRoles, roleName) => {
    //   return allowedRoles.some(role => roleName.includes(role));
    // };

    const roleName = _.get(currentUser, 'roleName', '');

    const allowedRoles = ['管理员', '高级用户', '普通用户'];
    const basecolumns = [
      {
        title: '序号',
        dataIndex: 'id',
        showFilter: false,
        align: 'center',
        render: (value, record, index) => {
          return `${(effectPageInfo.current - 1) * pagination.size + index + 1}`;
        },
      },
      {
        title: '账号',
        dataIndex: 'username',
        showFilter: true,
        align: 'center',
      },
      {
        title: '姓名',
        dataIndex: 'trueName',
        showFilter: true,
        align: 'center',
      },
      {
        title: '性别',
        dataIndex: 'sex',
        showFilter: true,
        checkbox: true,
        defaultValue: [0, 1],
        align: 'center',
        Option: [
          { value: 0, label: '男' },
          { value: 1, label: '女' },
        ],
        render: (text, record, index) => {
          return (
            <>
              <Tag color={`${text == 0 ? 'blue' : 'magenta'}`}>
                <TeamOutlined style={{ color: `${text == '0' ? 'blue' : 'red'}` }} />{' '}
                {text == '0' ? '男' : '女'}
              </Tag>
            </>
          );
        },
      },
      {
        title: '联系电话',
        dataIndex: 'telephone',
        showFilter: true,
        align: 'center',
        render: (value, record) => {
          return (
            <>
              <Tag icon={<PhoneOutlined rotate={100} />} color="cyan">
                {value}
              </Tag>
            </>
          );
        },
      },
      {
        title: '权限',
        dataIndex: 'roleName',
        showFilter: true,
        checkbox: true,
        defaultValue: ['admin', 'master', 'poweruser', 'user'],
        align: 'center',
        Option: [
          //{ value: 'admin', label: '超级管理员' },
          { value: 'master', label: '管理员' },
          { value: 'poweruser', label: '高级用户' },
          { value: 'user', label: '普通用户' },
        ],
      },
      {
        title: '住址',
        dataIndex: 'address',
        key: 'address',
      },
    ];
    let extraColumn = [];

    switch (roleName) {
      case '超级管理员':
        extraColumn = [
          {
            title: '操作',
            dataIndex: '',
            width: 200,
            align: 'center',
            render: (text, record, index) => {
              const a = '12';
              return (
                <div>
                  <Button
                    type={'primary'}
                    size={'small'}
                    style={{ marginRight: 5 }}
                    disabled={false}
                    onClick={() => {
                      this.changeModal('update', record);
                    }}
                  >
                    修改
                  </Button>
                  <Popconfirm
                    title="确定删除此用户?"
                    onConfirm={() => {
                      this.deleteUserById(record);
                    }}
                  >
                    <Button type={'primary'} danger size={'small'}>
                      删除
                    </Button>
                  </Popconfirm>
                </div>
              );
            },
          },
        ];
        break;

      case '管理员':
        extraColumn = [
          {
            title: '操作',
            dataIndex: '',
            width: 200,
            align: 'center',
            render: (text, record, index) => {
              const a = '12';
              return (
                <div>
                  <Button
                    type={'primary'}
                    size={'small'}
                    style={{ marginRight: 5 }}
                    disabled={false}
                    onClick={() => {
                      this.changeModal('update', record);
                    }}
                  >
                    修改
                  </Button>
                  <Popconfirm
                    title="确定删除此用户?"
                    onConfirm={() => {
                      this.deleteUserById(record);
                    }}
                  >
                    <Button type={'primary'} danger size={'small'}>
                      删除
                    </Button>
                  </Popconfirm>
                </div>
              );
            },
          },
        ];
        break;
      case '高级用户':
        extraColumn = [
          {
            title: '操作',
            dataIndex: '',
            width: 200,
            align: 'center',
            render: (text, record, index) => {
              const a = '12';
              return (
                <div>
                  <Button
                    type={'primary'}
                    size={'small'}
                    style={{ marginRight: 5 }}
                    disabled={true}
                    onClick={() => {
                      this.changeModal('update', record);
                    }}
                  >
                    修改
                  </Button>
                  <Popconfirm
                    title="确定删除此用户?"
                    onConfirm={() => {
                      this.deleteUserById(record);
                    }}
                  >
                    <Button type={'primary'} danger size={'small'} disabled={true}>
                      删除
                    </Button>
                  </Popconfirm>
                </div>
              );
            },
          },
        ];
        break;
      default:
        extraColumn = [];
    }

    columns = [...basecolumns, ...extraColumn];

    return (
      <PageHeaderWrapper>
        <Row span={24}>
          <Col span={24}>
            <Card title={formName} bordered={false} style={{ marginBottom: 10 }}>
              <Row>
                <Form
                  layout="inline"
                  labelAlign="left"
                  ref={this.formRef}
                  onFinish={(values) => {
                    this.handleRefreshData();
                  }}
                  style={{ marginBottom: 20 }}
                >
                  <FormFilter columns={columns} />
                  <Button
                    type="primary"
                    htmlType="submit"
                    style={{ marginRight: 20, marginTop: 8 }}
                  >
                    <SearchOutlined /> 查询
                  </Button>
                  <Button
                    type="primary"
                    style={{ marginTop: 8 }}
                    onClick={() => {
                      this.formRef && this.formRef.current && this.formRef.current.resetFields();
                    }}
                  >
                    <RedoOutlined />
                    重置
                  </Button>
                </Form>
              </Row>
              <Row>
                <Button
                  type="primary"
                  htmlType="button"
                  style={{ marginRight: 20, marginBottom: 15 }}
                  onClick={() => {
                    this.changeModal();
                  }}
                >
                  <UserAddOutlined /> 新增用户
                </Button>
                <Button type="primary" htmlType="button" danger>
                  <DeleteOutlined /> 批量删除
                </Button>
              </Row>
            </Card>
            <Card bordered={false}>
              <Table
                rowKey={'userId'}
                dataSource={users}
                loading={loading}
                rowSelection={[]}
                ref={this.tableRef}
                columns={columns}
                scroll={{ x: 'max-content' }}
                size={'small'}
                pagination={{
                  showQuickJumper: false,
                  showTotal: () => `共${pagination.total}条`,
                  pageSize: pagination.size,
                  total: pagination.total, //数据的总的条数
                  onChange: (current) => this.changePage(current), //点击当前页码
                }}
              />
            </Card>
          </Col>
        </Row>
        <UserModal
          visible={modalVisible}
          userDetail={userDetail}
          ref={this.modalRef}
          centered
          handleSumbit={(type) => {
            this.submitUserInfo(type);
          }}
          handleCancel={() => {
            this.changeModal();
            this.clearUserDetail();
          }}
        />
      </PageHeaderWrapper>
    );
  }
}
export default connect(({ userManage, user }) => ({
  number: userManage.number,
  users: userManage.users,
  loading: userManage.loading,
  pagination: userManage.pagination,
  selectedRowsKeys: userManage.selectedRowsKeys,
  modalVisible: userManage.modalVisible,
  userDetail: userManage.userDetail,
  versions: userManage.versions,
  currentUser: user.currentUser,
  effectPageInfo: userManage.effectPageInfo,
}))(UserManager);
